package com.ruoyi.common.yh.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.ruoyi.common.config.WxConfig;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@Component
public class WeixinInit {

    /*public static WxMaService weixinservice = null;*/
    @Autowired
    private WxConfig wxConfig;
    private static Map<String, WxMaService> maServices;
    @PostConstruct
    public void init() {
        List<WxConfig.Config> configs = wxConfig.getConfigs();
        if (configs == null) {
            throw new WxRuntimeException("添加下相关配置，注意别配错了！");
        }

        maServices = configs.stream()
                .map(a -> {
                    WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
                    // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
                    config.setAppid(a.getAppId());
                    config.setSecret(a.getSecret());
                    WxMaService service = new WxMaServiceImpl();
                    service.setWxMaConfig(config);
                    return service;
                }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
     /*   WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
       *//* config.setAppid("");
        config.setSecret("a821fb2b93e1969833ff27b49c553459");*//*
        config.setAppid(wxConfig.getAppId());
        config.setSecret(wxConfig.getSecret());
        weixinservice= new WxMaServiceImpl();
        weixinservice.setWxMaConfig(config);
        return Boolean.TRUE;*/
    }
    public static WxMaService getMaService(String appid) {
        WxMaService wxService = maServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        return wxService;
    }
  /*  public static WxMaService getWxMaService(){
        return weixinservice;
    }*/
}
